package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock{
    private StringRedisTemplate stringRedisTemplate;
    private String lock_name; //业务名称
    private long timeOutSec;
    public SimpleRedisLock(StringRedisTemplate stringRedisTemplate, String name){
        this.stringRedisTemplate = stringRedisTemplate;
        lock_name = name;
    }
    /**
     * 加载Lua脚本
     */
    private static final DefaultRedisScript<Long> LOCK_SCRIPT;
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;

    static {
        LOCK_SCRIPT = new DefaultRedisScript<>();
        LOCK_SCRIPT.setLocation(new ClassPathResource("get_lock.lua"));
        LOCK_SCRIPT.setResultType(Long.class);
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("release_lock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    private final String KEY_PREFIX = "lock:";
    private final String VALUE_PREFIX = UUID.randomUUID().toString(true)+"-";
    @Override
    public boolean tryLock(long timeoutSec) {
        this.timeOutSec = timeoutSec;
        // 1、确定key和value
        String key = KEY_PREFIX + lock_name;
        String value = VALUE_PREFIX + Thread.currentThread().getId();
        // 2、执行setnx
//        Boolean succ = stringRedisTemplate.opsForValue().setIfAbsent(key, value, timeoutSec, TimeUnit.SECONDS);
        Long result = stringRedisTemplate.execute(LOCK_SCRIPT,
                Collections.singletonList(key), value, Long.toString(timeoutSec));
//        System.out.println(result);
        return result!=null && result.equals(1L);
    }

    @Override
    public void unlock() {
        String key = KEY_PREFIX + lock_name;
        String value = VALUE_PREFIX + Thread.currentThread().getId();
//        String lock_value = stringRedisTemplate.opsForValue().get(key);
//        if(StrUtil.equals(value, lock_value)) // 线程只能释放自己持有的锁！
//            stringRedisTemplate.delete(key);
        // 调用LUA脚本释放锁,保证原子性
        stringRedisTemplate.execute(UNLOCK_SCRIPT,
                Collections.singletonList(key), value, Long.toString(this.timeOutSec));
    }
}
